/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.search.model;

import java.util.HashSet;
import java.util.LinkedList;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import offset.nodes.Constants;
import org.apache.jackrabbit.commons.iterator.NodeIteratorAdapter;

/**
 * Can be used for a node query result, that may contain the same nodes multiple times.
 *
 * Implementation is based on the UUID attribute, hence it will work only for nodes of type mix:referenceable.
 * 
 * @author Walter L�tgenau
 */
public class DistinctNodeIterator implements NodeIterator {

    NodeIterator distinctNodeIterator;

    public DistinctNodeIterator(NodeIterator ni) throws RepositoryException {
        LinkedList<Node> result = new LinkedList<Node>();
        HashSet<String> checker = new HashSet<String>();

        while (ni.hasNext()) {
            Node node = ni.nextNode();
            if (node.isNodeType(Constants.JCR_REFERENCEABLE))
                if (checker.contains(node.getUUID()))
                    continue;
                else
                    checker.add(node.getUUID());

            result.add(node);
        }

        distinctNodeIterator = new NodeIteratorAdapter(result);
    }

    public void remove() {
        distinctNodeIterator.remove();
    }

    public Object next() {
        return distinctNodeIterator.next();
    }

    public boolean hasNext() {
        return distinctNodeIterator.hasNext();
    }

    public void skip(long skipNum) {
        distinctNodeIterator.skip(skipNum);
    }

    public long getSize() {
        return distinctNodeIterator.getSize();
    }

    public long getPosition() {
        return distinctNodeIterator.getPosition();
    }

    public Node nextNode() {
        return distinctNodeIterator.nextNode();
    }
}
